from django.db import models
from django.contrib.auth.models import User
import hashlib
import json

class ErrorLog(models.Model):
    """错误日志模型"""
    
    LEVEL_CHOICES = [
        ('DEBUG', 'Debug'),
        ('INFO', 'Info'),
        ('WARNING', 'Warning'),
        ('ERROR', 'Error'),
        ('CRITICAL', 'Critical'),
    ]
    
    project = models.ForeignKey(
        'projects.Project', 
        on_delete=models.CASCADE, 
        related_name='error_logs',
        verbose_name='所属项目'
    )
    level = models.CharField(
        max_length=10, 
        choices=LEVEL_CHOICES, 
        default='ERROR',
        verbose_name='日志级别'
    )
    message = models.TextField(verbose_name='错误消息')
    stack_trace = models.TextField(blank=True, null=True, verbose_name='堆栈跟踪')
    timestamp = models.DateTimeField(auto_now_add=True, verbose_name='时间戳')
    user_agent = models.CharField(max_length=500, blank=True, null=True, verbose_name='用户代理')
    ip_address = models.GenericIPAddressField(blank=True, null=True, verbose_name='IP地址')
    url = models.URLField(blank=True, null=True, verbose_name='错误URL')
    
    # 新增字段
    fingerprint = models.CharField(max_length=64, db_index=True, verbose_name='错误指纹')
    source = models.CharField(max_length=500, blank=True, null=True, verbose_name='来源位置')
    user_id = models.CharField(max_length=100, blank=True, null=True, verbose_name='用户ID')
    session_id = models.CharField(max_length=100, blank=True, null=True, verbose_name='会话ID')
    
    # JSON字段存储复杂数据
    environment = models.JSONField(blank=True, null=True, verbose_name='环境信息')
    request_info = models.JSONField(blank=True, null=True, verbose_name='请求信息')
    breadcrumbs = models.JSONField(blank=True, null=True, verbose_name='用户行为路径')
    performance = models.JSONField(blank=True, null=True, verbose_name='性能数据')
    context = models.JSONField(blank=True, null=True, verbose_name='上下文信息')
    
    class Meta:
        db_table = 'error_logs'
        verbose_name = '错误日志'
        verbose_name_plural = '错误日志'
        ordering = ['-timestamp']
        indexes = [
            models.Index(fields=['project', '-timestamp']),
            models.Index(fields=['level', '-timestamp']),
            models.Index(fields=['fingerprint', '-timestamp']),
        ]
    
    def save(self, *args, **kwargs):
        # 自动生成错误指纹
        if not self.fingerprint:
            fingerprint_data = f"{self.message}{self.stack_trace or ''}{self.url or ''}"
            self.fingerprint = hashlib.md5(fingerprint_data.encode()).hexdigest()
        super().save(*args, **kwargs)
    
    def __str__(self):
        return f'{self.project.name} - {self.level} - {self.timestamp}'